<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\AuthRule;
use app\api\model\Users;
use Firebase\JWT\JWT;
use think\exception\ValidateException;
use think\facade\Config;
use think\Request;

class Login extends BaseController
{

    /**
     * @User: 刘海龙
     * @Date: 2021/2/25
     * @Time: 15:07
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户登录
     */
    public function userLogin(){
        $mobile   = $this->request->post('mobile');
        $password = $this->request->post('password');
        try {
            $this->validate(['mobile' => $mobile, 'password' => $password],
                \app\api\validate\Login::class);
            if (!$user = Users::where('mobile', $mobile)->find()) {
                return $this->response(403, '用户名不存在');
            }
            if (!$user->checkHashPassword($password)) {
                return $this->response(403, '密码错误');
            }
            $key             = "best_api";
            $time            = time();
            $expire          = $time + 14400; //过期时间
            $payload         = [
                "user_id" => $user->id,
                "iss"     => Config::get('common.http_url'),//签发组织
                "aud"     => "lhl",                   //签发作者
                "iat"     => $time,
                "nbf"     => $time,
                "exp"     => $expire,
            ];
            $jwt             = JWT::encode($payload, $key);
            $user->api_token = $jwt;
            $user->login_status = 1; //登录
            $user->save();
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
        return $this->response($user);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/2/25
     * @Time: 17:17
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 显示用户信息
     */
    public function userShow()
    {
        $id = $this->request->uid;
        $user = Users::find($id);
        if (is_null($user)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        $where = [];
        if (!in_array('*', $role_ids)) {
            //->where('is_open', AuthRule::OPEN_ONE)
            $where[] = array('id','in',implode(',', $role_ids));
        }
        $data = AuthRule::field('id,name')->where($where)->select()->toArray();
        $url = [];
        foreach ($data as $key=>$v){
            $url[] = $v['name'];
        }
        $user['url'] = implode(',',$url);
        $user['role'] = implode(',',$role_ids);
        return $this->response($user->toArray());
    }
}
